import os
import yaml
from conf.setting import FILE_PATH


def get_yaml_files(directory):
    yaml_files = []
    directory = os.path.abspath(directory)
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(".yaml") or file.endswith(".yml"):
                yaml_files.append(os.path.abspath(os.path.join(root, file)))
    # 对文件路径列表进行排序
    yaml_files.sort()
    return yaml_files


def get_data_yaml(file):
    # 将传入的文件路径转为绝对路径
    file = os.path.abspath(file)
    with open(file, 'r', encoding='utf-8') as f:
        yaml_data = yaml.safe_load(f)
        parent_folder = os.path.basename(os.path.dirname(file))
        file_name = os.path.splitext(os.path.basename(file))[0]  # 去掉文件后缀
        test_cases = []
        if len(yaml_data) <= 1:
            param = []
            base_info = yaml_data[0].get('baseInfo')
            test_case = yaml_data[0].get('testCase')
            for tc in test_case:
                lists = [base_info, tc, parent_folder, file_name]
                param.append(lists)
            return param
        else:
            for data in yaml_data:
                data.append(parent_folder)
                data.append(file_name)
                test_cases.append(data)
            return test_cases


def pytest_generate_tests(metafunc):
    # 只对包含 baseinfo 和 testcase 参数的测试函数进行参数化
    if 'baseinfo' in metafunc.fixturenames and 'testcase' in metafunc.fixturenames:
        yaml_files = get_yaml_files(FILE_PATH['testcase'])
        test_data = []
        for file in yaml_files:
            test_data.extend(get_data_yaml(file))
        print(test_data,'000')
        metafunc.parametrize('baseinfo,testcase,parent_folder,file_name', test_data)
